import { parseDateTime } from 'pub-bbx-utils';
import { CURRENCY_SUFFIX } from '@src/util/currency';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage();

/** 将form对象转成合同对象，用于提交表单 */
export function packToContract(fields, form, isTemporary, isOpen) {
  let contractAttribute = {}; // 合同自定义属性
  let productAttributeList = []; // 产品子表单
  let syncProductLists = [];
  let otherAttributeList = []; // 其它子表单
  let productWarrantyServiceList = []; // 产品质保服务项目

  let {
    customer = [],
    address = [],
    linkman = [],
    tags = [],
    otherAmount = '',
    discountAmount = '',
    contractAmount = '',
    contractName = '',
    effectiveTime = '',
    invalidTime = '',
    quotationAmount = '',
    procureAmount = '',
    managerPerson = [],
    otherAmountCurrency = 'CNY',
    discountAmountCurrency = 'CNY',
    contractAmountCurrency = 'CNY',
    quotationAmountCurrency = 'CNY',
    procureAmountCurrency = 'CNY'
  } = form || {};

  fields.forEach(field => {
    let { fieldName, isSystem, formType } = field || {};
    
    // 其它字表单
    if (formType === 'subSparePart') {
      let sparePartList = form[fieldName] || []; // 备件
      otherAttributeList = sparePartList.map(item => {
        return {
          businessId: item.id,
          businessType: 1
        }
      })
    }

    if (!isSystem && formType != 'product' && formType != 'subSparePart' && formType != 'productWarrantyService') {
      contractAttribute[field.fieldName] = form[field.fieldName];
    }

    if (!field.isSystem && field.formType == 'product') {
      let list = form[fieldName] || [];

      productAttributeList = list.map(item => {
        let params = {
          productId: item.id,
          contractAttribute: {},
        };

        field.subFormFieldList.forEach(field => {
          if (field.formType === 'relateProduct') return;
          if(field.fieldName === 'serviceMoney' && internationalGray) {
            const currencyName = field.fieldName + CURRENCY_SUFFIX;
            params.contractAttribute[currencyName] = item[[currencyName]];
          }

          params.contractAttribute[field.fieldName] = item[[field.fieldName]];
        });

        // 更新 并 开启产品质保 & 暂存
        if (item.syncProduct && isOpen) {
          syncProductLists.push(item.id);
          if (isTemporary) {
            params.contractAttribute.syncProduct = true;
          }
        }
        
        return params;
      });
    }

    // 产品质保服务
    if (!field.isSystem && field.formType == 'productWarrantyService') {
      let list = form[fieldName] || [];
      productWarrantyServiceList = list.map(item => {
        return {
          productWarrantyServiceId: item.id,
          contractAttribute: {
            ...item
          }
        };
      });
    }
  });

  let tagSimpleVOList = tags.map(item => {
    return {
      id: item.id,
      tagName: item.tagName,
    }
  });

  return {
    tagSimpleVOList,
    otherAmount: otherAmount,
    discountAmount: discountAmount,
    contractAmount: contractAmount,
    quotationAmount,
    procureAmount,
    quotationAmountCurrency,
    procureAmountCurrency,
    contractName,
    customerId: customer[0]?.value || '',
    linkmanId: linkman[0]?.id || '',
    addressId: address[0]?.id || '',
    manager: managerPerson,
    effectiveTime,
    invalidTime,
    contractAttribute,
    productAttributeList,
    syncProductLists,
    otherAttributeList,
    productWarrantyServiceList,
    otherAmountCurrency,
    discountAmountCurrency,
    contractAmountCurrency,
  };
}

/** 将合同对象转成form表单，用于初始化表单 */
export function packToForm(data) {
  let { address, customer, tagSimpleVOList} = data || {};
  let { id, name, lmId, lmName, lmPhone } = customer || {};
  
  let attribute = {
    ...data.attribute,
  };

  let form = {
    id: data.id,
    address: [address],
    customer: [
      {
        value: id,
        label: name,
        id: id,
      },
    ],
    linkman: [
      {
        id: lmId,
        name: lmName,
        phone: lmPhone,
      },
    ],
    tags: tagSimpleVOList || [],
  };
  return Object.assign(data, attribute, form);
}

// 生效日期小于失效日期
export function pickerEffectiveTimeOptions(pickerTime, endTime) {
  try {
    let selectedDate = parseDateTime(endTime);
    let pickerDate = pickerTime;

    if (!selectedDate || !pickerDate) return false;

    return pickerDate.getTime() > selectedDate.getTime();
  } catch (error) {
    console.log('pickerInvalidTimeOptions => error', error);
    return false;
  }
}

// 失效日期大于生效日期
export function pickerInvalidTimeOptions(pickerTime, endTime) {
  try {
    let selectedDate = parseDateTime(endTime);
    let pickerDate = pickerTime;

    if (!selectedDate || !pickerDate) return false;

    return pickerDate.getTime() < selectedDate.getTime();
  } catch (error) {
    console.log('pickerInvalidTimeOptions => error', error);
    return false;
  }
}
